<template>
  <div class="view-container">
    <card>
      <template #left>
        <TreeFilter
          label="deptName"
          title="部门列表"
          :data="deptTreeList"
          :border="false"
          @change="handleTreeChange"
        ></TreeFilter>
      </template>
      <template #right>
        <TableContainer
          :page-info="{ current: page, pageSize: pageSize, total: total }"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <template #searchCard>
            <SearchFrom :search-event="handleSearchEvent" />
          </template>
          <template #btnLeft>
            <el-button v-auth="['user:add:btn']" type="primary" @click="handleAdd">
              <el-icon>
                <Plus />
              </el-icon>
              新增
            </el-button>
            <el-button v-auth="['user:batch:delete:btn']" type="default" @click="handleBatchOperation('batchDeletion')">
              <el-icon>
                <Delete />
              </el-icon>
              批量删除
            </el-button>
            <el-button v-auth="['user:status:btn']" type="default" @click="handleBatchOperation('batchResetPasswords')">
              <el-icon>
                <Refresh />
              </el-icon>
              批量重置密码
            </el-button>
          </template>
          <el-table
            v-bind="$attrs"
            :data="[...tableData]"
            empty-text="暂无数据"
            :height="gridOptions.height"
            :show-overflow-tooltip="gridOptions.showOverflow"
            @selection-change="handleCheckboxChange"
          >
            <template #empty>
              <span>暂无数据</span>
            </template>
            <el-table-column
              v-for="item in gridOptions.columns"
              v-bind="$attrs"
              :type="item.type ? item.type : 'default'"
              :label="item.label"
              :prop="item.prop"
              :key="item.prop"
              :min-width="item.minWidth"
              :width="item.width"
              :fixed="item.fixed ? item.fixed : false"
              :header-align="item.headerAlign ? item.headerAlign : 'left'"
            >
              <template #default="{ row }">
                <el-tag v-if="item.slots === 'status'" :type="row.status ? 'primary' : 'info'">
                  {{ FROZEN_STATUS[row.status] }}
                </el-tag>
                <div class="w-full flex items-center justify-center" v-if="item.slots === 'controls'">
                  <el-button v-auth="['user:edit:btn']" link type="primary" @click="handleEdit(row)">
                    <el-icon>
                      <EditPen />
                    </el-icon>
                    修改
                  </el-button>
                  <el-button link v-auth="['user:status:btn']" type="danger" @click="handleChangeStatus(row)">
                    <el-icon>
                      <Unlock v-if="row.status === 'FROZEN'" />
                      <Lock v-else />
                    </el-icon>
                    {{ row.status === "FROZEN" ? "解冻" : "冻结" }}
                  </el-button>
                  <el-dropdown class="ml-3.5 custom-dropdown" @command="handleCommand($event, row)">
                    <span class="el-dropdown-link">
                      <el-icon><MoreFilled /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <template v-if="BUTTONS('user:delete:btn')">
                          <el-dropdown-item command="handleDelete">
                            <el-icon>
                              <Delete />
                            </el-icon>
                            删除
                          </el-dropdown-item>
                        </template>
                        <template v-if="BUTTONS('user:reset:btn')">
                          <el-dropdown-item command="handleResetPassword">
                            <el-icon>
                              <Refresh />
                            </el-icon>
                            重置密码
                          </el-dropdown-item>
                        </template>
                        <template v-if="BUTTONS('user:role:btn')">
                          <el-dropdown-item command="handleSetRole">
                            <el-icon>
                              <Setting />
                            </el-icon>
                            设置角色
                          </el-dropdown-item>
                        </template>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </TableContainer>
      </template>
    </card>
    <UserAdd ref="userAddRef" @close="handleClose"></UserAdd>
  </div>
</template>

<script lang="ts" setup>
import { FROZEN_STATUS } from "@/enums";
import { reactive, ref, onMounted } from "vue";
import SearchFrom from "./components/SearchFrom.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { getDeptTree } from "@/api/modules/dept";
import { Dept, User } from "@/api/interface";
import { changeUserStatus, deleteUser, getUserDetail, getUserList, resetPassword } from "@/api/modules/user";
import { useTableConfig } from "@/hooks/useTable";
import { useHandleData } from "@/hooks/useHandleData";
import UserAdd from "./components/Add.vue";
import { ElMessage } from "element-plus";
import TableContainer from "@/components/TableContainer/index.vue";
import Card from "@/components/Card/index.vue";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { usePagination } from "alova/client";

const userAddRef = ref();
const { BUTTONS } = useAuthButtons();

let searchForm = reactive<User.IUserParams>({});
const checkboxData = ref<User.IUser[]>([]);

const deptTreeList = ref<Dept.IDept[]>([]);

const { gridOptions } = useTableConfig({
  columns: [
    { type: "selection", width: 80 },
    { prop: "username", label: "用户名", minWidth: 120 },
    { prop: "nickname", label: "用户昵称", minWidth: 120 },
    { prop: "deptName", label: "归属部门", minWidth: 120 },
    {
      prop: "status",
      label: "状态",
      minWidth: 100,
      slots: "status"
    },
    { prop: "updateTime", label: "更新时间", minWidth: 150 },
    { prop: "name", label: "员工姓名", minWidth: 120 },
    { prop: "email", label: "电子邮箱", minWidth: 150 },
    { prop: "phone", label: "手机号", minWidth: 150 }
  ],
  checkboxLabelField: "username",
  controlsWidth: 200
});

onMounted(() => {
  initListData();
});

const getDeptTreeList = async () => {
  const { data } = await getDeptTree();
  deptTreeList.value = data;
};

const {
  data: tableData,
  page,
  pageSize,
  total,
  send
} = usePagination(
  (page, pageSize) =>
    getUserList({
      ...searchForm,
      current: page,
      size: pageSize
    }),
  {
    force: true,
    total: response => response.data?.pager?.total || 0,
    data: response => response.data?.records ?? []
  }
);

const handleSearchEvent = (form: User.IUserParams) => {
  searchForm = form;
  send();
};

// 处理部门树筛选
const handleTreeChange = (node: any) => {
  searchForm.deptId = node;
  send();
  console.log(tableData.value);
};
const handleAdd = () => {
  userAddRef.value?.openDialog();
};

const handleChangeStatus = async (row: User.IUser) => {
  try {
    const status = row.status === "FROZEN" ? "NORMAL" : "FROZEN";
    const result = await useHandleData(changeUserStatus, { id: row.id, status }, "修改状态");
    if (result) initListData();
  } catch (e) {
    console.log(e);
  }
};

const handleEdit = async (row: User.IUser) => {
  try {
    if (!row.id) return;
    const { data } = await getUserDetail(row.id);
    userAddRef.value?.openDialog("edit", data);
  } catch (e) {
    console.log(e);
  }
};

const handleDelete = async (row: User.IUser) => {
  try {
    if (!row.id) return;
    const result = await useHandleData(deleteUser, row.id, "删除");
    if (result) initListData();
  } catch (e) {
    console.log(e);
  }
};

const handleResetPassword = async (row: User.IUser) => {
  if (!row.id) return;
  await batchResetPasswords([row.id]);
};

const batchResetPasswords = async (ids: number[]) => {
  try {
    if (!ids.length) return ElMessage.warning("请选择需要重置密码的用户");
    const result = await useHandleData(resetPassword, { ids }, "重置密码");
    if (result) initListData();
  } catch (e) {
    console.log(e);
  }
};

const batchDeletion = async () => {
  try {
    const ids = checkboxData.value.map(item => item.id);
    if (!ids.length) return ElMessage.warning("请选择需要删除的用户");
    const result = await useHandleData(deleteUser, ids, "删除");
    if (result) initListData();
  } catch (e) {
    console.log(e);
  }
};

const handleBatchOperation = (command: string) => {
  const commands = {
    batchResetPasswords: batchResetPasswords,
    batchDeletion: batchDeletion
  };
  const ids = checkboxData.value.map(item => item.id);
  commands[command] && commands[command](ids);
};

const handleCheckboxChange = (records: User.IUser[]) => {
  checkboxData.value = [...records, ...checkboxData.value].filter(
    (item, index, arr) => arr.findIndex(t => t.id === item.id) === index
  );
  console.log(checkboxData.value);
};

const handleSetRole = async (row: User.IUser) => {
  try {
    if (!row.id) return;
    const { data } = await getUserDetail(row.id);
    console.log(userAddRef.value);
    userAddRef.value?.openDialog("edit", { ...data, setRole: true });
  } catch (e) {
    console.log(e);
  }
};

const handleCommand = (command: string, row: User.IUser) => {
  const commands = {
    handleDelete: handleDelete,
    handleResetPassword: handleResetPassword,
    handleSetRole: handleSetRole
  };
  commands[command] && commands[command](row);
};
const initListData = () => {
  getDeptTreeList();
};

// 处理分页
const handleSizeChange = (size: number) => {
  pageSize.value = size;
};
const handleCurrentChange = (current: number) => {
  page.value = current;
};

const handleClose = () => {
  initListData();
  send();
};
</script>

<style lang="scss">
.hidden-btn {
  background-color: #dedede;
  border-radius: 20px;
}
</style>
